package com.jiankang.askhealth.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.jiankang.askhealth.annotation.Permission;
import com.jiankang.askhealth.constant.SessionName;
import com.jiankang.askhealth.constant.UserType;
import com.jiankang.askhealth.core.user.bean.UserBean;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class PermissionInterceptor extends AbstractInterceptor{
	private static final Logger logger = Logger.getLogger(PermissionInterceptor.class);
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
        String methodName = invocation.getProxy().getMethod();
        Method method = invocation.getAction().getClass().getMethod(methodName);
        
        if(method != null && method.isAnnotationPresent(Permission.class)) {
        	Permission permission = method.getAnnotation(Permission.class);
            UserType[] userTypes = permission.userType();
            UserBean userBean = (UserBean) request.getSession().getAttribute(SessionName.LOGIN_USER);
            if (userBean == null) {
                return "goLogin";
            }
            UserType byType = UserType.getByType(userBean.getRole());
            switch (byType) {
                case SUPER_ADMIN:
                    return invocation.invoke();
                case NORMAL_USER:
                    for (UserType userType : userTypes) {
                        if (userType == byType) {
                            return invocation.invoke();
                        }
                    }
                    break;
            }
            return "goLogin";
        }
        if(logger.isDebugEnabled()) {
        	logger.debug("no permission");
        }
                
		return invocation.invoke();
	}
	
}
